import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 通过分享token获取表格
export async function GET(
  request: NextRequest,
  { params }: { params: { token: string } }
) {
  try {
    const shareToken = params.token

    const sheet = await prisma.sheet.findUnique({
      where: { shareToken },
      include: {
        owner: {
          select: {
            name: true,
            email: true
          }
        },
        cells: {
          orderBy: [
            { row: 'asc' },
            { column: 'asc' }
          ]
        }
      }
    })

    if (!sheet) {
      return NextResponse.json({ error: 'Invalid share link' }, { status: 404 })
    }

    if (!sheet.isPublic) {
      return NextResponse.json({ error: 'Sheet is not publicly accessible' }, { status: 403 })
    }

    return NextResponse.json({
      success: true,
      sheet: {
        id: sheet.id,
        title: sheet.title,
        description: sheet.description,
        allowEdit: sheet.allowEdit,
        owner: sheet.owner,
        cells: sheet.cells
      }
    })
  } catch (error) {
    console.error('Error fetching shared sheet:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
